package com.warmlight.voicepacket.ui.user.usercenter;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.umeng.analytics.MobclickAgent;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.base.BaseFragment;
import com.warmlight.voicepacket.data.eventbus.AudioCompleted;
import com.warmlight.voicepacket.data.eventbus.Login;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.http.HttpUtils;
import com.warmlight.voicepacket.http.ResponseData;
import com.warmlight.voicepacket.ui.imlm.adapter.TeaseAdapter;
import com.warmlight.voicepacket.ui.user.LoginRegistActivity;
import com.warmlight.voicepacket.utils.JSONUtils;
import com.warmlight.voicepacket.utils.MobClickHelper;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * 声音列表
 */
public class MySoundFragment extends BaseFragment {

    private SmartRefreshLayout smartrefreshlayout;
    private RecyclerView recyclerview_hot;
    private TeaseAdapter adapter;
    private int page;
    private RelativeLayout rl_login;
    private Button bt_login;
    private TextView tv_no_sound;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_sound,container,false);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void xxx(Login login){
//        initData();

        isLogin();

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initListener();
        isLogin();
    }

    private void isLogin() {
        if (SPUtils.isLogined()){
            smartrefreshlayout.setVisibility(View.VISIBLE);
            rl_login.setVisibility(View.GONE);
            initData();
            loadData(true);
        }else{
            smartrefreshlayout.setVisibility(View.GONE);
            rl_login.setVisibility(View.VISIBLE);
            bt_login.setVisibility(View.VISIBLE);
            bt_login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    MobclickAgent.onEvent(getContext(), MobClickHelper.PROFILE_VOICE_LOGIN);

                    Intent intent = new Intent(getContext(), LoginRegistActivity.class);
                    startActivity(intent);
                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //(sticky = true)
    public void onEvent(AudioCompleted data){

        if (adapter != null){
            adapter.clearPlay();
        }
    }
    private void initListener() {
        smartrefreshlayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadData(false);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                loadData(true);
            }
        });
    }

    /**
     * "data": {
     "tab": [{
     "id": 0,
     "title": "最热"
     },
     {
     "id": 1,
     "title": "最新"
     },
     {
     "id": 2,
     "title": "我的"
     }
     ],
     "has_more": true,
     "list": [{
     "id": "1",
     "type": "1",
     "title": "玩皮凉鞋正品真皮男士休闲鞋",
     "url": "https:\/\/wanpi-img.oss-cn-shanghai.aliyuncs.com\/wanpi_audio/1001/20180807192637/avator.pcm",
     "duration": "0",
     "is_hot": "0",
     "is_like": false,
     "star_num": "0",
     "add_time": "08-07 11:26",
     "author": {
     "uid": "1001",
     "nickname": "波",
     "avator": "https:\/\/wanpi-img.oss-cn-shanghai.aliyuncs.com\/wanpi\/1001\/20180807212451\/avator.png"
     }
     }]
     }
     * @param isRefresh
     */
    private void loadData(final boolean isRefresh) {
        String url = "";
        TreeMap<String,String> treeMap = new TreeMap<>();
        if (isRefresh){
            page = 1;
        }else{
            page ++;
        }
        url = HttpConfig.USER_AUDIO;
        treeMap.put("page",page+"");
        treeMap.put("pagesize","10");

        HttpClient.getInstance().postRxAndroidAES(url,treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {
                        if (HttpUtils.isCodeSuccess(responseData.getCode())){
                            String data = responseData.getData();
                            ArrayList<Map<String, String>> dataList = JSONUtils.getListMapByJson(data);
                            Map<String, String> map = dataList.get(0);
                            String list = map.get("list");
                            ArrayList<Map<String, String>> lists = JSONUtils.getListMapByJson(list);
                            for (int i=0;i<lists.size();i++){
                                lists.get(i).put("isplay","0");
                            }
                            if (isRefresh){
                                adapter.setItems(lists);
                                if (lists.size() == 0){
                                    rl_login.setVisibility(View.VISIBLE);
                                    bt_login.setVisibility(View.GONE);
                                    tv_no_sound.setVisibility(View.VISIBLE);
                                    tv_no_sound.setText("还未发布声音噢~快去试试~");
                                    smartrefreshlayout.setNoMoreData(true);
                                }else{
                                    rl_login.setVisibility(View.GONE);
                                }

                            }else{
                                if (lists.size()>0){
                                    adapter.addItems(lists);
                                }else{
                                    smartrefreshlayout.setNoMoreData(true);
                                }
                            }
                        }else{
                            ToastUtil.showShort(getContext(),responseData.getMsg());
                        }
                        smartrefreshlayout.finishRefresh(true);
                        smartrefreshlayout.finishLoadMore(true);
                    }

                    @Override
                    public void onError(Throwable e) {
                        smartrefreshlayout.finishRefresh(false);
                        smartrefreshlayout.finishLoadMore(false);
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void initData() {
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        recyclerview_hot.setLayoutManager(manager);
        adapter = new TeaseAdapter(getContext(),1);
        recyclerview_hot.setAdapter(adapter);
    }

    private void initView(View view) {
        smartrefreshlayout = (SmartRefreshLayout) view.findViewById(R.id.smartrefreshlayout);
        recyclerview_hot = view.findViewById(R.id.recyclerview_hot);
        rl_login = view.findViewById(R.id.rl_login);
        bt_login = view.findViewById(R.id.bt_login);
        tv_no_sound = view.findViewById(R.id.tv_no_sound);
    }
}
